const express = require('express');
const router = express.Router();
const Message = require('../models/Message');
const User = require('../models/User');
const auth = require('../middleware/auth');
const mongoose = require('mongoose');

// 调试中间件
router.use((req, res, next) => {
  console.log('💬 Messages route:', req.method, req.url);
  next();
});

// 获取会话列表 - 完全重写这个方法
router.get('/conversations', auth, async (req, res) => {
  try {
    console.log('📞 Getting conversations for user:', req.userId);
    
    // 方法1：使用更简单的查询
    const messages = await Message.find({
      $or: [
        { from: req.userId },
        { to: req.userId }
      ]
    })
    .populate('from', 'username avatar')
    .populate('to', 'username avatar')
    .sort({ createdAt: -1 });

    console.log(`📋 Found ${messages.length} messages for user`);

    // 手动构建会话列表
    const conversationMap = new Map();

    messages.forEach(message => {
      // 确定对方用户ID
      const otherUserId = 
        message.from._id.toString() === req.userId.toString() 
          ? message.to._id 
          : message.from._id;

      const otherUser = 
        message.from._id.toString() === req.userId.toString() 
          ? message.to 
          : message.from;

      // 如果还没有这个会话，或者这条消息更新，则更新会话
      if (!conversationMap.has(otherUserId.toString()) || 
          new Date(message.createdAt) > new Date(conversationMap.get(otherUserId.toString()).lastMessageTime)) {
        
        const unreadCount = message.to._id.toString() === req.userId.toString() && !message.isRead ? 1 : 0;

        conversationMap.set(otherUserId.toString(), {
          _id: otherUser,
          lastMessage: message.content,
          lastMessageTime: message.createdAt,
          unreadCount: unreadCount
        });
      }
    });

    const conversations = Array.from(conversationMap.values());
    
    console.log(`✅ Built ${conversations.length} conversations`);
    res.json(conversations);
  } catch (error) {
    console.error('❌ Get conversations error:', error);
    res.status(500).json({ error: '获取会话列表失败' });
  }
});

// 获取与特定用户的聊天记录 - 修复查询
router.get('/:userId', auth, async (req, res) => {
  try {
    const targetUserId = req.params.userId;
    console.log('💭 Getting messages between:', req.userId, 'and', targetUserId);

    // 确保用户ID是有效的ObjectId
    if (!mongoose.Types.ObjectId.isValid(targetUserId)) {
      return res.status(400).json({ error: '无效的用户ID' });
    }

    const messages = await Message.find({
      $or: [
        { from: req.userId, to: targetUserId },
        { from: targetUserId, to: req.userId }
      ]
    })
    .populate('from', 'username avatar')
    .populate('to', 'username avatar')
    .sort({ createdAt: 1 });

    console.log(`📨 Found ${messages.length} messages between users`);

    // 标记消息为已读（只标记对方发送的未读消息）
    await Message.updateMany(
      { 
        from: targetUserId, 
        to: req.userId, 
        isRead: false 
      },
      { $set: { isRead: true } }
    );

    res.json(messages);
  } catch (error) {
    console.error('❌ Get messages error:', error);
    res.status(500).json({ error: '获取消息失败' });
  }
});

// 发送消息 - 添加更多验证
router.post('/', auth, async (req, res) => {
  try {
    const { to, content, postId } = req.body;
    console.log('📤 Sending message from:', req.userId, 'to:', to, 'content:', content);

    // 验证接收用户ID
    if (!to || !mongoose.Types.ObjectId.isValid(to)) {
      return res.status(400).json({ error: '无效的接收用户ID' });
    }

    // 不能给自己发消息
    if (to === req.userId.toString()) {
      return res.status(400).json({ error: '不能给自己发送消息' });
    }

    // 检查接收用户是否存在
    const toUser = await User.findById(to);
    if (!toUser) {
      return res.status(404).json({ error: '接收用户不存在' });
    }

    const message = new Message({
      from: req.userId,
      to: to,
      content: content,
      post: postId
    });
    
    await message.save();
    console.log('✅ Message saved to database:', message._id);

    const populatedMessage = await Message.findById(message._id)
      .populate('from', 'username avatar')
      .populate('to', 'username avatar');
    
    console.log('✅ Message populated:', populatedMessage);
    res.json(populatedMessage);
  } catch (error) {
    console.error('❌ Send message error:', error);
    res.status(500).json({ error: '发送消息失败' });
  }
});

module.exports = router;